package com.example.cruds.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Component

public class OssUtils {
  private   String endpoint = "https://oss-cn-beijing.aliyuncs.com";

    // accesskey
   private String accessKeyId = "LTAI5tRn76cQ8B2NUC3nwcBb";
   private String accessKeySecret = "mEOwaj2gIbPUGAQKUlhabWWZ2cIdL4";

    // 填写Bucket名称，例如examplebucket。
    private String bucketName = "ful";

    // 实现图片上传到oss
    public String uploadoss(MultipartFile file) throws IOException{
        //获取文件的输入流
        InputStream inputStream = file.getInputStream();
        // 避免文件覆盖
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

        // 上传文件到oss
        OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
        ossClient.putObject(bucketName,fileName,inputStream);

        // 文件的访问路径
      String url =   endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1]+ "/" + fileName;
                //关闭ossclient
        ossClient.shutdown();
        return url;
    }
}
































